var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const { pageMixin } = require('../../../utils/page');

// 添加请求拦截器，监控所有API请求和响应
const originalRequest = wx.request;
wx.request = function(options) {
  console.log('请求URL:', options.url);
  console.log('请求方法:', options.method);
  console.log('请求数据:', options.data);

  // 保存原始success回调
  const originalSuccess = options.success;
  
  // 重写success回调
  options.success = function(res) {
    console.log('响应状态:', res.statusCode);
    console.log('响应数据:', res.data);
    
    // 调用原始success回调
    if (originalSuccess) {
      originalSuccess(res);
    }
  };
  
  return originalRequest(options);
};

Page({
  ...pageMixin,
  data: {
    activeTab: 0,
    tabs: ['全部', '待付款', '待接单', '待服务', '已关闭'],
    orders: [],
    userId: 1107,
    baseUrl: 'http://localhost:9205'
  },

  onLoad: function() {
    console.log('订单页面加载...');
    this.loadOrders();
  },

  onShow: function() {
    this.loadOrders();
  },

  onReady: function() {
    console.log('订单页面准备就绪');
  },

  // 切换标签
  onTabChange: function(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index
    });
    this.loadOrders();
  },

  // 加载订单数据
  loadOrders: function() {
    const tab = this.data.activeTab;
    let url = '';
    
    switch(tab) {
      case 0:
        url = `${this.data.baseUrl}/order/selectAll`;
        break;
      case 1:
        url = `${this.data.baseUrl}/order/selectStatus1`;
        break;
      case 2:
        url = `${this.data.baseUrl}/order/selectStatus2`;
        break;
      case 3:
        url = `${this.data.baseUrl}/order/selectStatus3`;
        break;
      case 4:
        url = `${this.data.baseUrl}/order/selectStatus4`;
        break;
    }

    console.log('开始请求订单数据...');
    console.log('请求URL:', url);
    console.log('请求参数:', { nid: this.data.userId });

    wx.request({
      url: url,
      method: 'GET',
      data: {
        nid: this.data.userId
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log('收到服务器响应:', res);
        
        if (res.statusCode === 200) {
          let orders = Array.isArray(res.data) ? res.data : [];
          console.log('转换后的订单数组:', orders);
          console.log('第一个订单数据样例:', orders.length > 0 ? orders[0] : '无订单');
          
          orders = orders.map(order => {
            console.log('处理订单数据:', order);
            // 检查字段是否存在，如果不存在则使用备选字段或默认值
            return {
              ...order,
              statusText: this.getStatusText(order.status),
              date: this.formatDate(order.date),
              doDate: this.formatDate(order.doDate || order.create_time || order.createdDate || order.createTime),
              // 确保地址和电话字段有值
              address: order.address || '暂无',
              phone: order.phone || '暂无'
            };
          });

          console.log('处理后的订单数据:', orders);

          this.setData({
            orders: orders
          });

          if (orders.length === 0) {
            wx.showToast({
              title: '暂无订单数据',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: '加载订单失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
      }
    });
  },

  // 获取状态文本
  getStatusText: function(status) {
    switch (status) {
      case 0:
        return '已取消';
      case 1:
        return '待付款';
      case 2:
        return '待接单';
      case 3:
        return '待服务';
      case 4:
        return '已关闭';
      default:
        return '未知状态';
    }
  },

  // 去支付
  goPay: function(e) {
    const order = e.currentTarget.dataset.order;
    wx.navigateTo({
      url: '/pages/order/payment/index?orderId=' + order.oid + '&amount=' + order.price
    });
  },

  // 确认收货
  confirmReceive: function(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认收货',
      content: '确认已收到服务吗？',
      success: (res) => {
        if (res.confirm) {
          // 调用后端接口更新订单状态
          wx.request({
            url: `${this.data.baseUrl}/order/updateStatus3`,
            method: 'GET',
            data: {
              id: orderId
            },
            success: (res) => {
              wx.showToast({
                title: '确认收货成功',
                icon: 'success'
              });
              // 重新加载订单列表
              this.loadOrders();
            },
            fail: (err) => {
              console.error('请求失败:', err);
              wx.showToast({
                title: '确认失败，请重试',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 修改订单日期
  modifyOrderDate: function(e) {
    const order = e.currentTarget.dataset.order;
    console.log('准备修改订单:', order);

    // 如果地址或电话为空，使用默认值
    if (!order.address || order.address === '暂无') {
      order.address = '河北省保定市万博广场';
    }
    if (!order.phone || order.phone === '暂无') {
      order.phone = '15630352072';
    }

    // 跳转到预约信息页面
    wx.navigateTo({
      url: `/pages/services/homecare/booking/index?orderId=${order.oid}`
    });
  },

  // 取消订单
  cancelOrder: function(e) {
    const orderId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '取消订单',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 调用后端接口取消订单
          wx.request({
            url: `${this.data.baseUrl}/order/deleteOrder`,
            method: 'GET',
            data: {
              oid: orderId
            },
            success: (res) => {
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              });
              // 重新加载订单列表
              this.loadOrders();
            },
            fail: (err) => {
              console.error('请求失败:', err);
              wx.showToast({
                title: '取消失败，请重试',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 去评价
  goRate: function(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/comment/comment?orderId=' + orderId
    });
  },

  // 格式化日期
  formatDate: function(dateStr) {
    if (!dateStr) return '暂无';
    
    try {
      console.log('格式化日期:', dateStr);
      const date = new Date(dateStr);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.error('无效的日期格式:', dateStr);
        return dateStr || '暂无'; // 如果无法解析，则返回原始字符串
      }
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hour = date.getHours().toString().padStart(2, '0');
      const minute = date.getMinutes().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}`;
    } catch (error) {
      console.error('格式化日期出错:', error);
      return dateStr || '暂无';
    }
  }
})